﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using FastData;

namespace WeigherMoudel
{
    public class HvcWeigher : Weigher
    {
        public VarSaveXML<ushort> StableCount;
        private System.Windows.Forms.TextBox textBox1;
        private NumericUpDown numericUpDown2;
        private Label label11;
        private Label label10;
        private Label label9;
        public VarSaveXML<float> StableStd;

        public override string ZeroCMD => "Z\r\n";

        public override string PowerOFFCMD => "OFF\r\n";

        public override string PowerONCMD => "ON\r\n";

        public HvcWeigher(string name, bool isShowForm = true) : base(name, isShowForm)
        {
            InitializeComponent();
        }

        public override void BeginCtor(string name)
        {
            StableStd = new VarSaveXML<float>("StableStd_" + name);
            StableCount = new VarSaveXML<ushort>("StableCount_" + name);
            base.BeginCtor(name);
        }

        private RetWeight ConvertString(string content)
        {
            float value = 0f;
            string ret = "";
            if (string.IsNullOrEmpty(content))
                return null;
            if (content.Contains("+") || content.Contains("-"))
            {
                int index = -1;
                if (content.Contains("+"))
                {
                    index = content.IndexOf('+');
                }
                else
                {
                    index = content.IndexOf('-');
                }
                if (content.Length - index >= 7)
                {
                 
                    ret = content.Substring(index, 8);
                    ret = ret.Replace(" ", "");
                    bool isfloat = float.TryParse(ret, out value);
                    if (isfloat)
                    {
                        bool isstable = CheckValueStable(value, StableCount.Value, StableStd.Value);
                        RetWeight retWeight = new RetWeight(isstable, ret, value);
                        return retWeight;
                    }
                    else
                    {
                        return null;
                    }
                }
                else
                {
                    return null;
                }
            }
            else
            {
                return null;
            }
        }

        List<float> listvar = new List<float>();
        private bool CheckValueStable(float var, ushort varCount, float std)
        {
           
            listvar.Add(var);
            if (listvar.Count > varCount)
            {
                listvar.RemoveRange(0, listvar.Count - varCount);
                float[] offsets = new float[listvar.Count];
                for (int i = 0; i < listvar.Count; i++)
                {
                    offsets[i] = listvar[i] - var;
                }
                float _std = GetSTD(offsets);
                if (_std < std)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }
        }

        public float GetSTD(float[] arrData)
        {
            float xSum = 0F;
            float xAvg = 0F;
            float sSum = 0F;
            float tmpStDev = 0F;
            int arrNum = arrData.Length;
            for (int i = 0; i < arrNum; i++)
            {
                xSum += arrData[i];
            }
            xAvg = xSum / arrNum;
            for (int j = 0; j < arrNum; j++)
            {
                sSum += ((arrData[j] - xAvg) * (arrData[j] - xAvg));
            }
            tmpStDev = Convert.ToSingle(Math.Sqrt((sSum / (arrNum - 1))).ToString());
            return tmpStDev;
        }

        internal override void Weightserial_OnReceiveData(string obj)
        {
            //if (obj.Contains("@RE"))
            //    return;
            //Thread.Sleep(100);
            lastupdatetime = DateTime.Now;
            if (obj.Length < 12) return;
            RetWeight retWeight = ConvertString(obj);
            if (retWeight == null)
                return;
 
            if (issendClear)  //正在发送清零指令的时候不接受
                return;
         

            ContempWeight = retWeight;
            base.Weightserial_OnReceiveData(obj);
        }

        private void InitializeComponent()
        {
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.numericUpDown2 = new System.Windows.Forms.NumericUpDown();
            this.label9 = new System.Windows.Forms.Label();
            this.label10 = new System.Windows.Forms.Label();
            this.label11 = new System.Windows.Forms.Label();
            this.panel1.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).BeginInit();
            this.panel2.SuspendLayout();
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).BeginInit();
            this.SuspendLayout();
            // 
            // numericUpDown1
            // 
            this.numericUpDown1.Location = new System.Drawing.Point(104, 92);
            // 
            // panel2
            // 
            this.panel2.Controls.Add(this.label11);
            this.panel2.Controls.Add(this.label10);
            this.panel2.Controls.Add(this.label9);
            this.panel2.Controls.Add(this.numericUpDown2);
            this.panel2.Controls.Add(this.textBox1);
            this.panel2.Location = new System.Drawing.Point(1, 131);
            this.panel2.Size = new System.Drawing.Size(227, 118);
            this.panel2.Controls.SetChildIndex(this.numericUpDown1, 0);
            this.panel2.Controls.SetChildIndex(this.textBox1, 0);
            this.panel2.Controls.SetChildIndex(this.numericUpDown2, 0);
            this.panel2.Controls.SetChildIndex(this.label9, 0);
            this.panel2.Controls.SetChildIndex(this.label10, 0);
            this.panel2.Controls.SetChildIndex(this.label11, 0);
            // 
            // textBox1
            // 
            this.textBox1.Location = new System.Drawing.Point(21, 93);
            this.textBox1.Name = "textBox1";
            this.textBox1.Size = new System.Drawing.Size(32, 21);
            this.textBox1.TabIndex = 14;
            this.textBox1.TextChanged += new System.EventHandler(this.textBox1_TextChanged);
            // 
            // numericUpDown2
            // 
            this.numericUpDown2.Location = new System.Drawing.Point(59, 92);
            this.numericUpDown2.Maximum = new decimal(new int[] {
            50,
            0,
            0,
            0});
            this.numericUpDown2.Name = "numericUpDown2";
            this.numericUpDown2.Size = new System.Drawing.Size(37, 21);
            this.numericUpDown2.TabIndex = 15;
            this.numericUpDown2.ValueChanged += new System.EventHandler(this.numericUpDown2_ValueChanged);
            this.numericUpDown2.MouseClick += new System.Windows.Forms.MouseEventHandler(this.numericUpDown2_MouseClick);
            // 
            // label9
            // 
            this.label9.AutoSize = true;
            this.label9.Location = new System.Drawing.Point(7, 78);
            this.label9.Name = "label9";
            this.label9.Size = new System.Drawing.Size(29, 12);
            this.label9.TabIndex = 16;
            this.label9.Text = "方差";
            // 
            // label10
            // 
            this.label10.AutoSize = true;
            this.label10.Location = new System.Drawing.Point(43, 77);
            this.label10.Name = "label10";
            this.label10.Size = new System.Drawing.Size(53, 12);
            this.label10.TabIndex = 17;
            this.label10.Text = "采样数量";
            // 
            // label11
            // 
            this.label11.AutoSize = true;
            this.label11.Location = new System.Drawing.Point(102, 77);
            this.label11.Name = "label11";
            this.label11.Size = new System.Drawing.Size(53, 12);
            this.label11.TabIndex = 18;
            this.label11.Text = "稳定次数";
            // 
            // HvcWeigher
            // 
            this.Name = "HvcWeigher";
            this.Size = new System.Drawing.Size(227, 249);
            this.Load += new System.EventHandler(this.HvcWeigher_Load);
            this.panel1.ResumeLayout(false);
            this.panel1.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown1)).EndInit();
            this.panel2.ResumeLayout(false);
            this.panel2.PerformLayout();
            ((System.ComponentModel.ISupportInitialize)(this.numericUpDown2)).EndInit();
            this.ResumeLayout(false);

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            float std = 0f;
            bool isfloat = float.TryParse(textBox1.Text, out std);
            if (isfloat)
            {
                StableStd.Value = std;
            }
            else
            {
                MessageBox.Show("输入稳定系数（标准方差）格式有误，需要输入float类型");
                textBox1.Text = StableStd.Value.ToString();
            }
        }

        private void panel1_Paint(object sender, PaintEventArgs e)
        {

        }

        private void HvcWeigher_Load(object sender, EventArgs e)
        {
            textBox1.Text = StableStd.Value.ToString();
            numericUpDown2.Value = StableCount.Value;
        }

        private void numericUpDown2_MouseClick(object sender, MouseEventArgs e)
        {
            
        }

        private void numericUpDown2_ValueChanged(object sender, EventArgs e)
        {
            StableCount.Value = (ushort)numericUpDown2.Value;
        }
    }
}
